package cn.com.ccxe.web;


import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.ccxe.core.db.ListPageDB;
import cn.com.ccxe.core.entity.CrawlExpression;
import cn.com.ccxe.core.entity.ListPageLink;
import cn.com.ccxe.core.entity.Website;
import cn.com.ccxe.dao.OperationStatus;
import cn.com.ccxe.service.WebsiteBussiness;
import cn.com.ccxe.web.form.WebsiteActionForm;

import com.ccxe.manage.service.CurrUserInfo;

public class WebsiteAction extends BasciAction {

	private static final long serialVersionUID = 4636983987993820160L;
	private static final Logger logger = LoggerFactory.getLogger(WebsiteAction.class);
	private static WebsiteBussiness bussiness = new WebsiteBussiness();
	private static String PATH = "/zebra/monitor/module/moduleAction";
	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void dispatch(HttpServletRequest req,
							HttpServletResponse resp)
			throws ServletException,
				   IOException {
		WebsiteActionForm actionForm = new WebsiteActionForm(req);
		//请求的方法
		String method = actionForm.getMethod();
		if(isEmpty(method)) {
			method = method.trim();
		}
		CurrUserInfo userInfo = actionForm.getUserInfo();
		if(userInfo == null) {
			logger.info("用户信息已过期，请重新登录！");
			resp.sendRedirect("/login.jsp");
			invalidateSession(req);
			return;
		}
		if(!isEmpty(method)) {
			show(req, resp, actionForm);
			return;
		}
		if("show".equals(method)) {
			show(req, resp, actionForm);
			return;
		}
		if("back".equals(method)) {
			back(req, resp, actionForm);
			return;
		}
		if("add".equals(method)) {
			add(req, resp, actionForm);
			return;
		}
		if("update".equals(method)) {
			update(req, resp, actionForm);
			return;
		}
		if("del".equals(method)) {
			del(req, resp, actionForm);
			return;
		}
		if("toUpdate".equals(method)) {
			toUpdate(req, resp, actionForm);
			return;
		}
		if("toAdd".equals(method)) {
			toAdd(req, resp, actionForm);
			return;
		}
	}
	
	private boolean isEmpty(String str) {
		return !StringUtils.isEmpty(str);
	}

	private void show(HttpServletRequest req,
						HttpServletResponse resp, 
						WebsiteActionForm actionForm)
			throws ServletException,
			   		IOException {
		int id = actionForm.getId();
		List<Website> moduleList = null;
		if(id <= 0) {
			moduleList = bussiness.getTopWebsite();
		} else {
			Website parent = bussiness.get(id);
			if(parent == null) {
				parent = new Website(id);
			}
			moduleList = bussiness.getChildWebsite(id);
			req.setAttribute("parentModule",parent);
		}
		req.setAttribute("moduleList", moduleList);
		forward(req, resp, "/zebra/monitor/module/show.jsp");
	}
	
	private void back(HttpServletRequest req,
					  HttpServletResponse resp, 
					  WebsiteActionForm actionForm)
			throws ServletException,
			   		IOException {
		//返回的应该为父模块的父模块下面的子模块信息。
		int id = actionForm.getParentId();
		int parentId = bussiness.getParentWebsiteId(id);
		StringBuilder path = new StringBuilder(PATH);
		path.append("?method=show&id=").append(parentId);
		logger.debug("PATH:"+path.toString());
		resp.sendRedirect(path.toString());
	}
	
	
	private void add(HttpServletRequest req,
					HttpServletResponse resp, 
					WebsiteActionForm actionForm)
			throws ServletException,
			IOException {
		Website module = paddedWebsite(actionForm);
		//添加采集规则
		if(actionForm.getIsList() == 1) {
			CrawlExpression rule = new CrawlExpression();
			rule.setModuleId(module.getId());
			rule.setArticleListExpre(actionForm.getArticleListExpre());
			rule.setListPageExpre(actionForm.getListPageExpre());
			rule.setDatePattern(actionForm.getDatePattern());
			rule.setDateExpre(actionForm.getDateExpre());
			module.setListPage(rule);
		}
		
		
		OperationStatus status = bussiness.add(module);
		switch (status) {
		case SUCCESS:
			if(module.getIsList() == 1) {
				addWebsite2ListPageDB(module);
			}
			logger.debug("添加站点:{}",module);
			forward(req, resp, PATH+"?method=show&id="+actionForm.getParentId());
			break;
		default:
			error(req, resp, "添加操作失败，请确认操作步骤是否正确！");
			break;
		}
	}
	
	private void toUpdate(HttpServletRequest req,
					HttpServletResponse resp, 
					WebsiteActionForm actionForm)
			throws ServletException,
			IOException {
		int id = actionForm.getId();
		Website module = bussiness.get(id);
		logger.debug("修改站点:{}",module);
		req.setAttribute("module", module);
		
		CrawlExpression rule = bussiness.getRule(id);
		req.setAttribute("rule",rule );
		forward(req, resp, "/zebra/monitor/module/update.jsp");
	}
	private void update(HttpServletRequest req,
					HttpServletResponse resp, 
					WebsiteActionForm actionForm)
			throws ServletException,
			IOException {
		Website module = paddedWebsite(actionForm);
		if(module.getIsList() == 1) {
			CrawlExpression rule = new CrawlExpression();
			rule.setModuleId(module.getId());
			rule.setArticleListExpre(actionForm.getArticleListExpre());
			rule.setListPageExpre(actionForm.getListPageExpre());
			rule.setModuleId(actionForm.getId());
			module.setListPage(rule);
		}
		OperationStatus status = bussiness.update(module);
		switch (status) {
		case SUCCESS:
			if(module.getIsList() == 1) {
				logger.debug("修改并添加至LIST_DB:{}",module);
				updateWebsite2ListPageDB(module);
			}
			StringBuilder redirectPath = new StringBuilder(PATH);
			redirectPath.append("?method=show&id=").append(module.getParentId());
			redirect(req, resp, redirectPath.toString());
			break;
		case RELATIONSHIP_EMPTY:
			error(req,resp,"该站点关联着其他的列表，无法修改成列表！");
			break;
		default:
			error(req, resp, "修改操作失败，请确认操作步骤是否正确！");
			break;
		}
	}
	private void del(HttpServletRequest req,
					HttpServletResponse resp, 
					WebsiteActionForm actionForm)
			throws ServletException,
			IOException {
		OperationStatus status = bussiness.del(actionForm.getId());
		switch (status) {
		case SUCCESS:
			redirect(req, resp, PATH+"?method=show&id="+actionForm.getParentId());
			break;
		default:
			error(req, resp, "删除操作失败，请确认操作步骤是否正确！");
			break;
		}
	}
	private void toAdd(HttpServletRequest req,
					HttpServletResponse resp, 
					WebsiteActionForm actionForm)
			throws ServletException,
			IOException {
		Website module = paddedWebsite(actionForm);
		req.setAttribute("parentId", module.getId());
		forward(req, resp, "/zebra/monitor/module/add.jsp");
	}
	
	private Website paddedWebsite(WebsiteActionForm form) {
		Website module = new Website();
		module.setId(form.getId());
		module.setParentId(form.getParentId());
		module.setName(form.getName());
		module.setDiscription(form.getDiscription());
		module.setIsList(form.getIsList());
		module.setIsMonitor(form.getIsMonitor());
		module.setPath(form.getPath());
		return module;
	}

	private void addWebsite2ListPageDB(Website module) {
		ListPageLink link = constructListPage(module);
		ListPageDB.getInstance().put(link.getPath(), link);
	}
	private void updateWebsite2ListPageDB(Website module) {
		ListPageLink link = constructListPage(module);
		link.setFetchTime(0);
		ListPageDB.getInstance().update(link.getPath(), link);
	}
	
	
	/**
	 * 将website的信息添加到ListPageLink中。
	 * @param website
	 * @return
	 */
	private ListPageLink constructListPage(Website website) {
		ListPageLink link = new ListPageLink();
		link.setPath(website.getPath());
		link.setModuleId(website.getId());
		link.setTitle(website.getName());
		link.setListPage(website.getListPage());
		return link;
	}
}
